<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-arrow-left"
      circle
      @click="$router.replace('/student')"
    ></el-button>

    <el-form
      :model="updateStudent"
      :rules="rules"
      ref="studentForm"
      label-width="100px"
      class="update-ruleForm"
      style="width: 100%; height: 100%"
      label-position="right"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="updateStudent.name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select
          class="filter-item"
          v-model="updateStudent.gender"
          placeholder="请选择"
        >
          <el-option
            v-for="option in genderOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select> </el-form-item
      ><el-form-item label="学校" prop="school">
        <!-- <el-input v-model="updateStudent.school"></el-input> -->
        <el-autocomplete
          class="inline-input"
          v-model="updateStudent.school"
          :fetch-suggestions="querySearchSchool"
          placeholder="请输入内容"
          value-key="schoolname"
        >
        </el-autocomplete>
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-autocomplete
          class="inline-input"
          v-model="updateStudent.major"
          :fetch-suggestions="querySearchMajor"
          placeholder="请输入内容"
          value-key="majorsname"
        >
        </el-autocomplete> </el-form-item
      ><el-form-item label="年级" prop="grade">
        <el-select
          class="filter-item"
          v-model="updateStudent.grade"
          placeholder="请选择"
        >
          <el-option
            v-for="option in gradeOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select> </el-form-item
      ><el-form-item label="学历" prop="education">
        <el-select
          class="filter-item"
          v-model="updateStudent.education"
          placeholder="请选择"
        >
          <el-option
            v-for="option in educationOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select> </el-form-item
      ><el-form-item label="学习方向" prop="direction">
        <el-select
          class="filter-item"
          v-model="updateStudent.direction"
          placeholder="请选择"
        >
          <el-option
            v-for="option in directionOptions"
            :key="option.type"
            :label="option.name"
            :value="option.type"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="身份号码" prop="id_number">
        <el-input v-model="updateStudent.id_number"></el-input>
      </el-form-item>
      <el-form-item label="电话号码" prop="phone">
        <el-input v-model="updateStudent.phone"></el-input> </el-form-item
      ><el-form-item label="家长名" prop="parent">
        <el-input v-model="updateStudent.parent"></el-input> </el-form-item
      ><el-form-item label="家长联系电话" prop="parent_phone">
        <el-input
          v-model="updateStudent.parent_phone"
        ></el-input> </el-form-item
      ><el-form-item label="家庭住址" prop="address">
        <el-input v-model="updateStudent.address"></el-input> </el-form-item
      ><el-form-item label="QQ号码" prop="qq">
        <el-input v-model="updateStudent.qq"></el-input> </el-form-item
      ><el-form-item label="所在班级" prop="class">
        <el-select
          class="filter-item"
          v-model="updateStudent.class"
          placeholder="请选择"
        >
          <el-option
            v-for="option in classOptions"
            :key="option._id"
            :label="option.classname"
            :value="option.classname"
          ></el-option>
        </el-select> </el-form-item
      ><el-form-item label="入学时间" prop="addmission_date">
        <el-date-picker
          v-model="updateStudent.addmission_date"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker> </el-form-item
      ><el-form-item label="教师" prop="teacher_id">
        <el-select
          class="filter-item"
          v-model="updateStudent.teacher_id"
          placeholder="请选择"
        >
          <el-option
            v-for="option in teacherOPtions"
            :key="option._id"
            :label="option.name"
            :value="option._id"
          ></el-option>
        </el-select> </el-form-item
      ><el-form-item label="学管" prop="manager_id">
        <el-select
          class="filter-item"
          v-model="updateStudent.manager_id"
          placeholder="请选择"
        >
          <el-option
            v-for="option in managerOptions"
            :key="option._id"
            :label="option.name"
            :value="option._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图片" prop="pictures">
        <!-- <el-input v-model="updateStudent.pictures"></el-input>  -->
        <el-upload
          :action="baseApi + '/manage/img/upload'"
          list-type="picture-card"
          :auto-upload="true"
          :file-list="fileList"
          name="image"
          accept="image/*"
          :on-change="handleChange"
          multiple:true
        >
          <i slot="default" class="el-icon-plus"></i>
          <div slot="file" slot-scope="{ file }">
            <img
              class="el-upload-list__item-thumbnail"
              :src="file.url"
              alt=""
            />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)"
              >
                <i class="el-icon-zoom-in"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)"
              >
                <i class="el-icon-download"></i>
              </span>
              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)"
              >
                <i class="el-icon-delete"></i>
              </span>
            </span>
          </div>
        </el-upload>
        <el-dialog :visible.sync="pictureDialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <!-- <el-input v-model="updateStudent.note"></el-input> -->
        <vue-tinymce v-model="updateStudent.note" :setting="setting" />
      </el-form-item>

      <!-- <el-select
        class="filter-item"
        v-model="updateStudent.teacher_id"
        placeholder="请选择"
      >
        <el-option
          v-for="option in teacherOptions"
          :key="option._id"
          :label="option.name"
          :value="option._id"
        ></el-option>
      </el-select> -->

      <el-form-item>
        <el-button
          type="primary"
          @click="
            updateStudent._id == null
              ? addDate('studentForm')
              : updateDate('studentForm')
          "
          >立即创建</el-button
        >
        <el-button @click="resetForm('studentForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import studentApi from "@/api/student";
import schoolApi from "@/api/school";
import classApi from "@/api/class";
import userApi from "@/api/user";
import majorApi from "@/api/majors";
export default {
  data() {
    var validatePhone = (rule, value, callback) => {
      value = value.trim();
      const pwdReg =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!pwdReg.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };
    var validateIdNumber = (rule, value, callback) => {
      value = value.trim();
      const _IDRe18 =
        /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      const _IDre15 =
        /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
      if (_IDRe18.test(value) || _IDre15.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正确的身份证号码"));
      }
    };
    return {
      setting: {
        //去除文件栏
        menubar: false,
        //定义工具栏
        toolbar:
          "undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontselect fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | superscript subscript | removeformat |",
        toolbar_drawer: "sliding",
        quickbars_selection_toolbar:
          "removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor",
        //工具栏模块
        plugins: "link image media table lists fullscreen quickbars imagetools",
        language: "zh_CN", //本地化设置
        height: 350,
      },
      baseApi: process.env.VUE_APP_BASE_API,
      baseUrl: process.env.VUE_APP_SERVICE_URL,
      pictureDialogVisible: false,
      dialogImageUrl: "",
      disabled: false,
      fileList: [],
      updateStudent: {
        _id: null,
        name: "", //姓名
        gender: "", //性别
        school: "", //学校
        major: "", //专业
        grade: "", //年级
        education: "", //学历
        direction: "", //学习方向
        id_number: "", //身份号码
        phone: "", //电话号码
        parent: "", //家长名
        parent_phone: "", //家长联系电话
        address: "", //家庭住址
        qq: "", //QQ号码
        class: "", //所在班级
        addmission_date: "", //入学时间
        teacher_id: "", //教师
        manager_id: "", //学管
        pictures: [], //照片数组
        note: "", //备注信息
      },
      rules: {
        name: [{ required: true, message: "请填写姓名", trigger: "blur" }],
        gender: [{ required: true, message: "请填写性别", trigger: "blur" }],
        direction: [
          { required: true, message: "请填写学习方向", trigger: "blur" },
        ],
        id_number: [
          { trigger: ["blur", "change"], validator: validateIdNumber },
        ],
        phone: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: validatePhone,
          },
        ],
        class: [{ required: true, message: "请填写班级", trigger: "blur" }],
        teacher_id: [
          { required: true, message: "请填写授课教师", trigger: "blur" },
        ],
        manager_id: [
          { required: true, message: "请填写学管", trigger: "blur" },
        ], 
      },

      //性别
      genderOptions: [
        { type: "0", name: "男" },
        { type: "1", name: "女" },
      ],

      //年级
      gradeOptions: [
        { type: "1", name: "大一" },
        { type: "2", name: "大二" },
        { type: "3", name: "大三" },
        { type: "4", name: "大四" },
        { type: "5", name: "研究生" },
      ],
      //学历
      educationOptions: [
        { type: "1", name: "专科" },
        { type: "2", name: "本科" },
        { type: "3", name: "硕士" },
        { type: "4", name: "社会" },
      ],
      directionOptions: [
        { type: "1", name: "web前端" },
        { type: "2", name: "Java" },
        { type: "3", name: "UI/UE" },
        { type: "4", name: "C/C++" },
      ],
      //学校
      schoolOptions: [],
      majorOptions: [],
      classOptions: [],
      teacherOPtions: [],
      managerOptions: [],
      userAll: [],
    };
  },
  mounted() {
    this.getUserList();
    this.getclassList();
    this.getMajorList();
    this.getSchoolList();
    this.getStudent();
    console.log("123",this.studentForm);
  },
  components: {},

  methods: {
    handleRemove(file, fileList) {
      studentApi.reqDeleteImg(file.name).then((response) => {
        const resp = response.data;
        if (resp.status === 0) {
          /* 项目中遇到的问题 删除文件时总删除最后一个文件   匹配不到 */
          // this.fileList.splice(this.fileList.indexOf(file.name));
          this.fileList.splice(this.fileList.indexOf(file), 1);
        }
      });
    },
    handleDownload(file, fileList) {
      console.log(file);
    },
    handlePictureCardPreview(file, fileList) {
      this.dialogImageUrl = file.url;
      this.pictureDialogVisible = true;
    },
    handleChange(file, fileList) {
      if (file.status === "success") {
        const result = file.response;
        if (result.status === 0) {
          const { name, url } = result.data;
          file = fileList[fileList.length - 1];
          file.name = name;
          file.url = url;
        }
      }
      this.fileList = fileList;
    },
    getImgs() {
      return this.fileList.map((file) => file.name);
    },
    querySearchSchool(queryString, cb) {
      var schoolOptions = this.schoolOptions;
      var results = queryString
        ? schoolOptions.filter(this.createFilterSchool(queryString))
        : schoolOptions;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    querySearchMajor(queryString, cb) {
      var majorOptions = this.majorOptions;
      var results = queryString
        ? majorOptions.filter(this.createFilterMajor(queryString))
        : majorOptions;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilterSchool(queryString) {
      return (restaurant) => {
        return (
          restaurant.schoolname
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) == 0
        );
      };
    },
    createFilterMajor(queryString) {
      return (restaurant) => {
        return (
          restaurant.majorname
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) == 0
        );
      };
    },
    addDate(formName) {
      console.log(this.updateStudent);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateStudent.pictures = this.getImgs();
          studentApi.add(this.updateStudent).then((response) => {
            const resp = response.data;
            if (resp.status === 0) {
              this.$router.replace("/student");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    updateDate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateStudent.pictures = this.getImgs();
          console.log("123",this.updateStudent);
          studentApi.update(this.updateStudent).then((response) => {
            const resp = response.data;
            if (resp.status === 0) {
              this.$router.replace("/student");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    getStudent() {
      const _id  = this.$route.params.id;
      console.log('_id',_id);
      if (_id !== "-1") {
        studentApi.getById(_id).then((response) => {
          const resp = response.data;
          console.log('resp',resp);
          if (resp.status === 0) {
            this.updateStudent = resp.data;
            const { pictures } = resp.data;
            console.log(pictures);
            if (pictures && pictures.length > 0) {
              this.fileList = pictures.map((img, index) => ({
                uid: -index,
                name: img,
                status: "success",
                url: this.baseUrl + "/upload/" + img,
              }));
            }
          }
        });
      }
    },

    //获取所有用户列表
    getUserList() {
      userApi.getUserAll().then((response) => {
        const res = response.data;
        if (res.status === 0) {
          this.userAll = res.data;
          this.userAll.forEach((item) => {
            if (item.role_id === "6322979ee6ce6366206d0aad") {
              this.teacherOPtions.push(item);
            } else if (
              item.role_id === "632297a3e6ce6366206d0ab0"
            ) {
              this.managerOptions.push(item);
            }
          });
        }
      });
    },
    //获取班级列表
    getclassList() {
      classApi.getclassAll().then((response) => {
        const res = response.data;
        if (res.status === 0) {
          this.classOptions = res.data;
          console.log(this.classOptions);
        }
      });
    },
    //获取学校列表
    getSchoolList() {
      schoolApi.getSchoolList().then((response) => {
        const res = response.data;
        if (res.status === 0) {
          this.schoolOptions = res.data.data;
          console.log('schoolOption',this.schoolOptions);
        }
      });
    },
    //获取所有专业
    getMajorList() {
      majorApi.getmajorsList().then((response) => {
        const res = response.data;
        if (res.status === 0) {
          this.majorOptions = res.data.data;
        }
        console.log(this.majorOptions)
      });
    },
  },
};
</script>

<style scoped>
.el-input {
  width: 500px;
}
</style>